<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/7
 * Time: 19:05
 */

namespace app\components;
use app\models\Order;
use app\models\User;
use Yii;

class DealOrder
{
    protected $orderType;
    protected $orderData;

    /**
     * @param $orderData
     * @param $orderType
     */
    public function setOrder($orderData, $orderType)
    {
        $this->orderType = $orderType;
        $this->orderData = $orderData;
    }

    public function addOrder()
    {
        if ($this->orderType == 'withPet')
        {
            $result = $this->dealPetOrder();
        }
        return $result;
    }

    /**
     * 处理订单
     * @return array
     * @throws \yii\db\Exception
     */
    protected function dealPetOrder()
    {
        $userPetRow = $this->orderData;
        $redis = Yii::$app->redis;
        $key = 'order_pet_'.$userPetRow->puid;
        if ($redis->get($key)) {
            return ['code' => 10001, 'msg' => '订单已被其它用户购买'];
        }
        $redis->set($key, 1, 30);//锁定订单60秒
        if (Yii::$app->user->identity->balance < $userPetRow->price) {
            return ['code' => 10002, 'msg' => '您的余额不足，请及时充值'];
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $userId = Yii::$app->user->getId();
            $price = $userPetRow->price;
            $User = new User();
            $userResult = $User->reduceBlance($userId, $price);//买家扣除余额
            $serviceFee = round($price * 0.05);//手续费金额
            $incomme = $price - $serviceFee;//卖家收入
            $sailResult = $User->increaseBlance($userPetRow->user_id, $incomme);//卖家增加余额
            $order = new Order();
            $orderResult = $order->addPetUserOrder($userPetRow);//增加玩客订单

            $userPetRow->user_id = $userId;
            $userPetRow->updted_at = time();
            $userPetRow->price = 0;
            $userPetRow->auction_status = 0;
            $userPetResult = $userPetRow->save();//转让玩客猪所属人
            if (!empty($userResult) && !empty($sailResult) && !empty($userPetResult) && !empty($orderResult)) {
                $transaction->commit();
            }
            return ['code' => 10000, 'msg' => '购买成功'];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }
}